package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.CreateDiatyTask;
import com.xgkj.diyiketang.task.UploadImage;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by XCKJ_Paladowow on 2016/8/1.
 */
public class FaRiZhiActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private ImageButton addPicButton;
    private LinearLayout addlayout;
    private LinearLayout addlayout2;
    PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 0;
    private static final int CHOOSE_REQUEST = 11;
    private static final int CROP_REQUEST = 2;
    private File mFile;
    private String local_url;
    private static final String CAMERA_FILE = "diyiketang/img";
    int start = 0;
    private int uploadImageTaskId = -1;
    private TextView mPubBtn;
    private RelativeLayout mLimitLayout;
    private String mLimitString;
    private TextView mLimitText;
    private String mPicString = "";
    private String mContentEdit;
    private EditText contentEdit;
    private String scope;
    private int createTaskId = -1;
    private TextView mBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.farizhi);
        mContext = this;
        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "IMG" + System.currentTimeMillis() + ".jpg";
        mFile = new File(folder, fileName);
        initView();
    }

    private void initView() {
        mBack = (TextView) findViewById(R.id.back);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        addPicButton = (ImageButton) findViewById(R.id.add_pic_btn);
        addlayout = (LinearLayout) findViewById(R.id.pic_list);
        addlayout2 = (LinearLayout) findViewById(R.id.pic_list2);
        addPicButton.setOnClickListener(this);
        mPubBtn = (TextView) findViewById(R.id.publish);
        mPubBtn.setOnClickListener(this);
        mLimitLayout = (RelativeLayout) findViewById(R.id.limit_layout);
        mLimitLayout.setOnClickListener(this);
        mLimitText = (TextView) findViewById(R.id.limit);
        contentEdit = (EditText) findViewById(R.id.jianjie_content);
        initPopWindow();
    }


    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (!mFile.exists()) {
                    return;
                }
                Uri uri = Uri.fromFile(mFile);
                startPhotoZoom(uri);
                break;

            case CHOOSE_REQUEST:
                if (data == null)
                    return;
                Uri choose_uri = data.getData();
                startPhotoZoom(choose_uri);
                break;

            case CROP_REQUEST:
                if (data == null)
                    return;

                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                start++;

                if (start <= 3) {
                    ImageView iv = new ImageView(mContext);
                    iv.setLayoutParams(new LinearLayout.LayoutParams(ViewUtil.dip2px(mContext, 100),
                            ViewUtil.dip2px(mContext, 100)));
                    iv.setPadding(10, 0, 0, 0);
                    iv.setImageBitmap(bitmap);
                    addlayout.addView(iv);
                }
                if (start == 3) {
                    addlayout.removeView(addPicButton);
                    addlayout2.addView(addPicButton);
                }
                if (start > 3) {
                    ImageView iv = new ImageView(mContext);
                    iv.setLayoutParams(new LinearLayout.LayoutParams(ViewUtil.dip2px(mContext, 100),
                            ViewUtil.dip2px(mContext, 100)));
                    iv.setPadding(10, 0, 0, 0);
                    iv.setImageBitmap(bitmap);
                    addlayout2.addView(iv);
                }
                if (start == 6) {
                    addPicButton.setVisibility(View.GONE);
                }


                BufferedOutputStream out = null;

                try {
                    out = new BufferedOutputStream(new FileOutputStream(mFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                if (bitmap != null && out != null){
                    bitmap.compress(Bitmap.CompressFormat.JPEG,80,out);
                }


                uploadImage(mFile.getAbsolutePath());
                break;

            case 5:
                if (data != null) {
                    mLimitString = data.getExtras().getString("LIMIT");
                    scope = data.getExtras().getString("SCOPE");
                    mLimitText.setText(mLimitString);
                }

                break;

            default:
                break;
        }
    }

    private void uploadImage(String path) {
        UploadImage task = new UploadImage(path);
        task.addListener(uploadImageListener);
        uploadImageTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void doPublish() {
        CreateDiatyTask ctask = new CreateDiatyTask(mContentEdit, mPicString, scope);
        ctask.addListener(uploadImageListener);
        createTaskId = getEatShowApp().getTaskManager().addTask(ctask);
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            local_url = GetImagePathUtil.getPath(mContext, uri);
            uri = Uri.fromFile(new File(local_url));
        }

        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST);
    }

    private TaskEventListener uploadImageListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == uploadImageTaskId) {
                String url = ((JSONObject) data).getString("imageId");
                mPicString += url + ";";

            } else if (taskId == createTaskId) {
                ToastUtil.showMessage(mContext, "发表成功!");
                finish();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_pic_btn:
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(FaRiZhiActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;

            case R.id.takephoto:
                popWindow.dismiss();
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera_intent
                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
                break;
            case R.id.publish:

                if (checkInput()) {
                    doPublish();
                }
                break;
            case R.id.limit_layout:
                Intent cintent = new Intent(mContext, ShareLimitActivity.class);
                cintent.putExtra("SCOPE",scope);
                startActivityForResult(cintent, 5);
                break;
        }
    }


    private boolean checkInput() {
        mContentEdit = contentEdit.getText().toString();
        if (TextUtils.isEmpty(mContentEdit)) {
            Toast.makeText(mContext, "内容不能为空",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(scope)) {
            Toast.makeText(mContext, "请选择朋友圈权限",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
}
